package com.happy3w.game.guess_num;

import java.text.MessageFormat;

public class NumMatcher {
    public MatchResult match(int secretNum, int guessNum) {
        String secretN = formatNum(secretNum);
        String guessN = formatNum(guessNum);

        int a = countA(secretN, guessN);
        int existNum = countExistNum(secretN, guessN);
        int b = existNum - a;
        String evaluation = MessageFormat.format("{0}A{1}B", a, b);

        boolean success = a == secretN.length();
        return new MatchResult(success, evaluation);
    }

    private int countExistNum(String secretN, String guessN) {
        int b = 0;
        for (int i = 0; i < guessN.length(); i++) {
            if (secretN.indexOf(guessN.charAt(i)) >= 0) {
                b++;
            }
        }
        return b;
    }

    private int countA(String secretN, String guessN) {
        int a = 0;
        for (int i = 0; i < secretN.length(); i++) {
            if (secretN.charAt(i) == guessN.charAt(i)) {
                a++;
            }
        }
        return a;
    }

    private String formatNum(int secretNum) {
        return MessageFormat.format("{0,number,#}", secretNum);
    }
}
